<!DOCTYPE html>
<html>
<head>
<title>This is the test document.docx</title>
<link rel="stylesheet" href="testdata.css" type="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript">
//{{{
//
var opentext = {};
opentext.webviewer = {};

opentext.webviewer.drawing = (function() {
	return {

      placeImage: function() {
         var img = window.document.createElement('img');
			var canvas = document.getElementById('canvas_form');
         img.setAttribute('id', 'documentbodyimage');
         img.setAttribute( 'src', 'img/PDF.png');
         img.setAttribute('height', '1350px' );
         img.setAttribute('width', '850px' );
         canvas.appendChild(img);
      },


		rotate_left: function() {
   		var e2, e3;
			e2 = document.getElementById('canvas_anno');
			e3 = document.getElementById('canvas_form');
			e2.setAttribute( 'style', '-webkit-transform: scale(1.0) rotate(270deg) translateY(250px) translateX(250px); -ms-transform: scale(1.0) rotate(270deg) translateY(250px) translateX(250px)' );
			e3.setAttribute( 'style', '-webkit-transform: scale(1.0) rotate(270deg) translateY(250px) translateX(250px); -ms-transform: scale(1.0) rotate(270deg) translateY(250px) translateX(250px)' );
		},

		rotate_right: function() {
   		var e2, e3;
			e2 = document.getElementById('canvas_anno');
			e3 = document.getElementById('canvas_form');
   		e2.setAttribute( 'style', '' );
   		e3.setAttribute( 'style', '' );
		}
	};
}());


function init () {
	var canvas = document.getElementById('myDrawing_anno');
				
	// Check the element is in the DOM and the browser supports canvas
	if(!(canvas && canvas.getContext)) {
      return;
   }
      
	// Initaliase a 2-dimensional drawing context
	var context = canvas.getContext('2d');

   // The pencil tool instance for drawing on the screen.
   opentext.webviewer.pencil = new FreehandTool( canvas, context );

   // Load the base image (localy froom the web server only)
   opentext.webviewer.drawing.placeImage();

	// Attach the mousedown, mousemove and mouseup event listeners.
   // I am attaching the event to the canvas itself, which is not changed
   // by transformation at all. So the offsetX/Y are comming always
   // in correct coordinate system.
	canvas.addEventListener('mousedown', ev_canvas, false);
	canvas.addEventListener('mousemove', ev_canvas, false);
	canvas.addEventListener('mouseup',   ev_canvas, false);
}
		
	// This painting object works like a drawing pencil which tracks the mouse movements.
   // The mouse movement is stored in a contained inside the object itself. The data
   // gets removed by each initilization cycle and by each use.
   function	FreehandTool ( cnv, ctx ) {
		  var tool = this;
		  this.started = false;
        this.canvas = cnv;
        this.context = ctx;
        this.anno = []; // contained for annotation. Technically it is array of arrays. 
		  this.anno.counter = 0; // count how many annotations were put on the drawing.
		
        // This method restored the saved annotation and put them back in the drawing. Attantion, 
        // this method is destructive and you can read the local container just one. I is a poor
        // man example using push() and shift() array access control, which make it a LIFO queue.
        this.redrawMyAnnotation = function() {
	         var an;
	         var el;
	         if( typeof tool.anno == "undefined" )
		         return;

	         tool.context.globalAlpha= "1.0";
	         tool.context.strokeStyle = "#000000";

         	while( an = tool.anno.shift() ) {
	         	el = an.shift();
		         tool.context.beginPath();
		         tool.context.moveTo(el.x, el.y);
					while( el = an.shift() ) {
						tool.context.lineTo(el.x,el.y);
						tool.context.stroke();
					}
					tool.context.closePath();
				}
				tool.anno = [];
				tool.anno.counter = 0;
			};

		  // This is called when you start holding down the mouse button.
		  // This starts the pencil drawing.
        // For simplisity reasons, this function also impletemts two extra 
        // operation:
        // 1) clean the drawing canvas
        // 2) place the recored annotation on the canvas.
		  this.mousedown = function (ev) {
            if( true == ev.ctrlKey ) { // pressing CTRL and clicking into canvas will clear it.
               console.log("canvas deleted!");
               tool.context.clearRect(0, 0, tool.canvas.width, tool.canvas.height );
               return;
            } 
            if( true == ev.shiftKey ) { // pressing ALT and clicking into cnavas will restore the recorded annotations.
               console.log("captured annotation redrawn");
               tool.redrawMyAnnotation();
               return;
            }
            // this is the drawing section. When clicking in the canvas the drawing will be initiated. 
            // The drawing itself is done once in 100ms, so mot every tiny movement of the mouse 
            // translates into freehand element.
	         tool.context.globalAlpha= "1.0";
	         tool.context.strokeStyle = "#000000";
	         tool.context.beginPath();
	         tool.context.moveTo(ev._x, ev._y);
            tool.lastX = ev._x;
            tool.lastY = ev._y
            tool.intervalID = setInterval( "opentext.webviewer.pencil.doLine()", 100 );
	         tool.started = true;
				tool.anno[tool.anno.counter] = [];
		  };
		
		  // This function is called every time you move the mouse. Obviously, it only 
		  // draws if the tool.started state is set to true (when you are holding down 
		  // the mouse button).
		  this.mousemove = function (ev) {
		    if (tool.started) {
            tool.lastX = ev._x;
            tool.lastY = ev._y
		    }
		  };

        // This is the drawing method, is not called each time the mousemove event fires,
        // just every 100 ms. Otherwise the datastream generated for freehand annotation
        // would be flooding the buffer ...
        this.doLine = function() {
            console.log("painting");
		      tool.context.lineTo(tool.lastX, tool.lastY);
		      tool.context.stroke();
            tool.anno[tool.anno.counter].push( { "x":tool.lastX, "y":tool.lastY } ); 
        }
		
		  // This is called when you release the mouse button.
        // stop recording the annotation coordinates and stop drawing.
        // increase the annotation counter so next time a new annotation
        // gets recorded.
		  this.mouseup = function (ev) {
		    if (tool.started) {
	         tool.context.closePath();
		      tool.mousemove(ev);
		      tool.started = false;
	         clearInterval(tool.intervalID);
				tool.anno.counter++;
		    }
		  };
	}
		
	// The general-purpose event handler. This function just determines the mouse 
	// position relative to the canvas element. It is the key fucntion for capturing
   // the correct coordinates for the paited object. The event is bound to the canvas
   // itself, which is not rotated. I rotate the div contained of the canvas itself!
   // Additionally, the key is to use CSS pixels to read the mouse position. That will
   // give you always the right coordinates regardless what CSS transformation is applied.
   // Attention, apply CSS transformation only, everything else is trasforming the data, 
   // which is what is definitively dont want to get.
   // The only operation that must happen to logged coordinates is the scalling based
   // on the scalling used to generate the image. You can do this operation before
   // uploading to archive server, you don't need to to place the annotation.
   function ev_canvas (ev) {
 		if (! ev.hasOwnProperty('offsetX')) {
        var curleft = curtop = 0;
	         if (ev.offsetParent) {
			      var obj=ev;
					do {
						curleft += obj.offsetLeft;
						curtop += obj.offsetTop;
					} while (obj = obj.offsetParent);
				}
         ev.offsetX=ev.layerX-curleft;
        	ev.offsetY=ev.layerY-curtop;
    	}
	
	 	if (ev.offsetX || ev.offsetX == 0) { // Opera || Maxthron || Chrome || IE10 are OK. Mozila not tested yet.
         ev._x = ev.offsetX;
         ev._y = (ev.offsetY );
      } else {
         console.err("Cannot determine the mouse ccordinates");
         return;
      }
		
      // Call the event handler of the pencil tool to draw.
      var func = opentext.webviewer.pencil[ev.type];
		if( typeof func == 'function' ) {
         func(ev);
      } else {
			console.error(" reflection did not work.");
		}
   }



//}}}
</script>
</head>
<body onLoad=init()>


<div id="canvas_form" class="canvas_form">
<!--
<canvas id="myDrawing_form" width="850" height="1350">
<p>Your browser does not support canvas</p>
</canvas>
-->
</div>
<div id= "canvas_anno" class="canvas_anno">
<canvas id="myDrawing_anno" width="850" height="1350">
<p>Your browser does not support canvas</p>
</canvas>
</div>

<div id="form">
Rotate: [<a href="JavaScript: opentext.webviewer.drawing.rotate_left()">left</a>]&nbsp;&nbsp;[<a href="JavaScript: opentext.webviewer.drawing.rotate_right()">right</a>]<br/>
</div>

</body>
</html>
